//
//  UploadViewController.m
//  UEAssistant
//
//  Created by mac on 2017/4/13.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "UploadViewController.h"
#import <QuickLook/QuickLook.h>
#import<CommonCrypto/CommonDigest.h>
#import "UploadProductCell.h"
#import "UploadSelectModel.h"
#import "CreatNewProjectViewController.h"
#import "UploadSetViewController.h"



@interface UploadViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    NSMutableArray              *_dataSource;
    NSInteger                   _currentPage;
    NSMutableArray              *_languageArray;

}

@property (nonatomic, strong) QLPreviewController *previewVC;
@property (nonatomic, strong) UIButton      *preview;
@property (nonatomic, strong) UIButton      *cancel;
@property (nonatomic, strong) UIButton      *upload;
@property (nonatomic, strong) NSString      *mine;
@property (nonatomic, strong) UITableView   *tableView;
@property (nonatomic, strong) UIImageView                                   *view_data_nil;
@property (nonatomic, strong) UILabel                                       *text_data_nil;
@property (nonatomic, strong) UIButton          *saveProject;
@property (nonatomic, strong) NSString      *sourceKey;
@property (nonatomic, strong) NSString      *targetKey;
@property (nonatomic, strong) NSString      *selectSorceValue;
@property (nonatomic, strong) NSString      *projectID;

@property (strong, nonatomic)NSString *currentOwnerId;
@end

@implementation UploadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setData];
}

- (void)setUI{

    self.view.backgroundColor = RGB(250, 250, 250, 1);
    self.title = @"项目";
    
    [self.view addSubview:self.tableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;

    
    UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, Screen_Height -86*Radio-64, Screen_Width, 86*Radio)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.shadowColor = [UIColor grayColor].CGColor;
    whiteView.layer.shadowOffset = CGSizeMake(0, -1);
    whiteView.layer.shadowOpacity = 0.2;
    whiteView.layer.shadowRadius = 1;
    [self.view addSubview:whiteView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 10*Radio, Screen_Width-15, 15)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = RGB(170, 170, 170, 1);
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
    label.text = @"选择上传路径";
    [whiteView addSubview:label];
    
    UIButton *createNewProject = [UIButton buttonWithType:UIButtonTypeSystem];
    createNewProject.frame = CGRectMake(15, 30*Radio, 160*Radio, 45*Radio);
    createNewProject.backgroundColor = RGB(57, 207, 150, 1);
    [createNewProject setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createNewProject setTitle:@"新建项目" forState:UIControlStateNormal];
    createNewProject.layer.cornerRadius = 3;
    [createNewProject addTarget:self action:@selector(createNewProjectClicked) forControlEvents:UIControlEventTouchUpInside];
    createNewProject.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
    [whiteView addSubview:createNewProject];
    
    _saveProject = [UIButton buttonWithType:UIButtonTypeSystem];
    _saveProject.frame = CGRectMake(Screen_Width - 15-160*Radio, 30*Radio, 160*Radio, 45*Radio);
    [_saveProject setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_saveProject setTitle:@"保存至" forState:UIControlStateNormal];
    _saveProject.layer.cornerRadius = 3;
    [_saveProject addTarget:self action:@selector(saveByHttpToServer) forControlEvents:UIControlEventTouchUpInside];
    _saveProject.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
    _saveProject.backgroundColor = RGB(237,239, 240, 1);
    [_saveProject setEnabled:NO];
    [whiteView addSubview:_saveProject];
}

- (void)setData{

//    NSLog(@"MD5 == %@",[self getFileMD5WithPath:[shareData.filepath substringFromIndex:7]]);
    _currentPage = 1;
    _dataSource = [NSMutableArray array];
    
    NSString *mainBundleDirectory=[[NSBundle mainBundle] bundlePath];
    NSString *path=[mainBundleDirectory stringByAppendingPathComponent:@"alllanguage.json"];
    NSURL *url=[NSURL fileURLWithPath:path];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
//    NSLog(@"语言---%@",[self toArrayOrNSDictionary:data]);
    _languageArray = [NSMutableArray arrayWithArray:[self toArrayOrNSDictionary:data][@"result"]];
    
    [self getDataRequest];
}

- (void)getDataRequest{
    
    [LSProgressHUD showLoadingToView:self.navigationController.view];
    _dataSource = [NSMutableArray array];
    _currentPage = 1;
    NSDictionary *dic = @{@"page":@"1",@"limit":@"8"};
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:productList_connector] params:dic successHandler:^(id responseObject) {
        
//        TGLog(@"productList----%@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            
            for (int i = 0; i < ((NSArray *)responseObject[@"result"]).count; i++) {
                NSDictionary *dic = responseObject[@"result"][i];
                UploadSelectModel *model = [[UploadSelectModel alloc]initWithDictionary:dic];
                model.isSelected = NO;
                [_dataSource addObject:model];
            }

            [LSProgressHUD hiddenLoading:self.navigationController.view];
            [self.tableView reloadData];
            
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(250, 250, 250, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
            }
        }
        else{
            
            NSLog(@"message -- %@",responseObject[@"message"]);
            [LSProgressHUD hiddenLoading:self.navigationController.view];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];

            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(250, 250, 250, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
                
            }
            
        }
        if (responseObject) {
            
        }
        
    } falureHandler:^(NSError *error) {
        
        [LSProgressHUD hiddenLoading:self.navigationController.view];
        if (_dataSource.count == 0) {
            self.tableView.backgroundColor = [UIColor whiteColor];
            [self.tableView addSubview:self.view_data_nil];
            [self.tableView addSubview:self.text_data_nil];
        }
        else{
            self.tableView.backgroundColor = RGB(250, 250, 250, 1);
            [self.view_data_nil removeFromSuperview];
            [self.text_data_nil removeFromSuperview];
            
        }
        
    }];
    
}


#pragma ---------- Mjrefresh -------------

- (void)loadNewTopic{
    
    _currentPage = 1;
    NSDictionary *dic = @{@"page":@"1",@"limit":@"8"};
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:productList_connector] params:dic successHandler:^(id responseObject) {
        
        NSLog(@"productList----%@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            [_dataSource removeAllObjects];
            for (int i = 0; i < ((NSArray *)responseObject[@"result"]).count; i++) {
                NSDictionary *dic = responseObject[@"result"][i];
                UploadSelectModel *model = [[UploadSelectModel alloc]initWithDictionary:dic];
                model.isSelected = NO;
                [_dataSource addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(250, 250, 250, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
                
            }
            
        }
        else{
            
            [self.tableView.mj_header endRefreshing];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(250, 250, 250, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
                
            }
            
        }
        
    } falureHandler:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        if (_dataSource.count == 0) {
            self.tableView.backgroundColor = [UIColor whiteColor];
            [self.tableView addSubview:self.view_data_nil];
            [self.tableView addSubview:self.text_data_nil];
        }
        else{
            self.tableView.backgroundColor = RGB(250, 250, 250, 1);
            [self.view_data_nil removeFromSuperview];
            [self.text_data_nil removeFromSuperview];
            
        }
        
        NSLog(@"%@",error);
    }];
}

- (void)loadMoreTopic{
    
    _currentPage += 1;
    NSString *currentPage = [NSString stringWithFormat:@"%ld",(long)_currentPage];
    NSDictionary *dic = @{@"page":currentPage,@"limit":@"8"};
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:productList_connector] params:dic successHandler:^(id responseObject) {
        NSLog(@"---------%@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            if (((NSArray *)responseObject[@"result"]).count > 0) {
                for (int i = 0; i < ((NSArray *)responseObject[@"result"]).count; i++) {
                    NSDictionary *dic = responseObject[@"result"][i];
                    UploadSelectModel *model = [[UploadSelectModel alloc]initWithDictionary:dic];
                    model.isSelected = NO;
                    [_dataSource addObject:model];
                }
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }else{
                
                _currentPage -= 1;
                [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"已经加载完全部数据" andTitleColor:[UIColor whiteColor] andCancel:NO];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else{
            
            _currentPage -= 1;
            [self.tableView.mj_footer endRefreshing];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
        }
    } falureHandler:^(NSError *error) {
        
        _currentPage -= 1;
        [self.tableView.mj_footer endRefreshing];
        NSLog(@"error == == == %@",error);
    }];
}



#pragma mark -- tableview代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UploadProductCell *cell = [[UploadProductCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    cell.nameLabel.text = ((UploadSelectModel *)_dataSource[indexPath.row]).project_name;
    cell.timeLabel.text = ((UploadSelectModel *)_dataSource[indexPath.row]).dealline_time;
    cell.langugeType.text = [NSString stringWithFormat:@"%@ -> %@",((UploadSelectModel *)_dataSource[indexPath.row]).sourcelangname,((UploadSelectModel *)_dataSource[indexPath.row]).targetlangname];
;
    
    if (((UploadSelectModel *)_dataSource[indexPath.row]).isSelected) {
        cell.seletImage.image = [UIImage imageNamed:@"选中"];
    }else{
        cell.seletImage.image = [UIImage imageNamed:@"选择"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [_dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx != indexPath.row) {
            ((UploadSelectModel *)obj).isSelected = NO;
            UploadProductCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
            lastCell.seletImage.image = [UIImage imageNamed:@"选择"];
        }
    }];
    
    if (((UploadSelectModel *)_dataSource[indexPath.row]).isSelected == YES) {
        UploadProductCell *nowCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
        nowCell.seletImage.image = [UIImage imageNamed:@"选择"];
        ((UploadSelectModel *)_dataSource[indexPath.row]).isSelected = NO;
        _saveProject.backgroundColor = RGB(237,239, 240, 1);
        [_saveProject setEnabled:NO];

    }else{
    
        UploadProductCell *nowCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
        nowCell.seletImage.image = [UIImage imageNamed:@"选中"];
        ((UploadSelectModel *)_dataSource[indexPath.row]).isSelected = YES;
        _saveProject.backgroundColor = RGB(57, 186, 241, 1);
        [_saveProject setEnabled:YES];
        _projectID = ((UploadSelectModel *)_dataSource[indexPath.row]).project_id;
        _currentOwnerId = ((UploadSelectModel *)_dataSource[indexPath.row]).owner_id;
        _selectSorceValue = ((UploadSelectModel *)_dataSource[indexPath.row]).sourcelangname;
        NSLog(@"原语言对 == %@",_selectSorceValue);
    }
}

#pragma mark -- Event

- (void)createNewProjectClicked{

    self.hidesBottomBarWhenPushed = YES;
    CreatNewProjectViewController *vc = [[CreatNewProjectViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)saveByHttpToServer{

    //获取语言对
    [_languageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj[@"dictionaryValue"] isEqualToString:_selectSorceValue]) {
            _sourceKey = _languageArray[idx][@"dictionaryKey"];
        }
    }];
    
    UploadSetViewController *vc = [[UploadSetViewController alloc]init];
    vc.sourcelangkey = _sourceKey;
    vc.projectId = _projectID;
    vc.owner_id = _currentOwnerId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
    
}


#pragma mark -- getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 6, Screen_Width, Screen_Height -92*Radio-64) style:UITableViewStylePlain];
        _tableView.backgroundColor = RGB(250, 250, 250, 1);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.rowHeight = 120*Radio;

    }
    return _tableView;
}

- (UIImageView *)view_data_nil{
    
    if (!_view_data_nil) {
        _view_data_nil = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width/2+50*Radio, Screen_Width/2)];
        _view_data_nil.image = [UIImage imageNamed:@"项目"];
        _view_data_nil.center = CGPointMake(self.view.center.x, Screen_Height/4);
    }
    return _view_data_nil;
}

- (UILabel *)text_data_nil{
    
    if (!_text_data_nil) {
        _text_data_nil = [[UILabel alloc]initWithFrame:CGRectMake(0, _view_data_nil.frame.origin.y+_view_data_nil.frame.size.height+20*Radio, Screen_Width, 30)];
        _text_data_nil.backgroundColor = [UIColor clearColor];
        _text_data_nil.text = @"暂时还没有参与的项目";
        _text_data_nil.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
        _text_data_nil.textColor = [UIColor grayColor];
        _text_data_nil.textAlignment = NSTextAlignmentCenter;
        
    }
    return _text_data_nil;
}

@end
